package com.ryujung.binary_tree.leetCode_103;

import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {

    /**
     * 思路：
     * 与层序遍历类似的，使用队列来存放每层节点，
     * 然后使用一个flag来判断是正序遍历还是逆序遍历队列
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();

        // 非空判断
        if (root == null) return res;

        ArrayDeque<TreeNode> que = new ArrayDeque<>();
        que.add(root);
        // normal: FIFO , reverse: FILO
        boolean reverseFlag = true;

        while (!que.isEmpty()) {
            int curSize = que.size();
            List<Integer> curList = new ArrayList<>();
            for (int i = 0; i < curSize; i++) {
                TreeNode node = reverseFlag ? que.pollFirst() : que.pollLast();
                curList.add(node.val);

                if (reverseFlag) {
                    if (node.left != null) {
                        que.offerLast(node.left);
                    }
                    if (node.right != null) {
                        que.offerLast(node.right);
                    }
                } else {
                    if (node.right != null) {
                        que.offerFirst(node.right);
                    }
                    if (node.left != null) {
                        que.offerFirst(node.left);
                    }
                }
            }
            res.add(curList);
            reverseFlag = !reverseFlag;
        }
        return res;
    }
}